
// 处理页面加载时的选项卡状态
document.addEventListener('DOMContentLoaded', function () {
    // 从URL参数获取当前激活的选项卡
    const urlParams = new URLSearchParams(window.location.search);
    const activeTab = urlParams.get('tab');

    if (activeTab) {
        const tabElement = document.getElementById(`${activeTab}-tab`);
        if (tabElement) {
            const tab = new bootstrap.Tab(tabElement);
            tab.show();
        }
    }

    // 监听选项卡切换事件，更新URL
    const tabEls = document.querySelectorAll('button[data-bs-toggle="tab"]');
    tabEls.forEach(tabEl => {
        tabEl.addEventListener('shown.bs.tab', function (event) {
            const tabName = event.target.id.replace('-tab', '');
            const url = new URL(window.location);
            url.searchParams.set('tab', tabName);
            window.history.replaceState({}, '', url);
        });
    });
});

// 获取CSRF token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 显示编辑用户名模态框
function showEditNameModal() {
    const modal = new bootstrap.Modal(document.getElementById('editNameModal'));
    modal.show();
}

// 保存用户名
async function saveUserName() {
    const newName = document.getElementById('editNameInput').value.trim();

    if (!newName) {
        alert('用户名不能为空');
        return;
    }

    try {
        const response = await fetch('/api/setuserinfo/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({
                type: 'name',
                value: newName
            })
        });

        if (response.ok) {
            // alert('用户名更新成功');
            location.reload();
        } else {
            alert('更新失败，请重试');
        }
    } catch (error) {
        console.error('更新失败:', error);
        alert('更新失败，请重试');
    }
}

// 显示编辑个人介绍模态框
function showEditDescriptionModal() {
    const modal = new bootstrap.Modal(document.getElementById('editDescriptionModal'));
    modal.show();
}

// 保存个人介绍
async function saveUserDescription() {
    const newDescription = document.getElementById('editDescriptionInput').value.trim();

    try {
        const response = await fetch('/api/setuserinfo/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({
                type: 'description',
                value: newDescription
            })
        });

        if (response.ok) {
            // alert('个人介绍更新成功');
            location.reload();
        } else {
            alert('更新失败，请重试');
        }
    } catch (error) {
        console.error('更新失败:', error);
        alert('更新失败，请重试');
    }
}

// 全局变量存储选择的图片ID
let selectedAvatarImageId = null;
let selectedCoverImageId = null;

// 预览头像图片
async function previewAvatarImage() {
    const imageId = document.getElementById('avatarImageId').value;

    if (!imageId) {
        alert('请输入图片ID');
        return;
    }

    try {
        const response = await fetch(`/api/getimagebyid/?id=${imageId}`);

        if (response.ok) {
            // 创建对象URL来显示图片
            const blob = await response.blob();
            const imageUrl = URL.createObjectURL(blob);

            document.getElementById('avatarPreview').src = imageUrl;
            document.getElementById('avatarPreviewContainer').style.display = 'block';
            document.getElementById('avatarPreviewError').style.display = 'none';
            selectedAvatarImageId = parseInt(imageId);
            console.log("Selected ", selectedAvatarImageId, " ? ", imageId);

        } else {
            document.getElementById('avatarPreviewContainer').style.display = 'none';
            document.getElementById('avatarPreviewError').style.display = 'block';
            document.getElementById('avatarPreviewError').textContent = '图片不存在或无法访问';
            selectedAvatarImageId = null;
        }
    } catch (error) {
        console.error('预览失败:', error);
        document.getElementById('avatarPreviewContainer').style.display = 'none';
        document.getElementById('avatarPreviewError').style.display = 'block';
        document.getElementById('avatarPreviewError').textContent = '预览失败，请重试';
        selectedAvatarImageId = null;
    }
}

// 预览头图图片
async function previewCoverImage() {
    const imageId = document.getElementById('coverImageId').value;

    if (!imageId) {
        alert('请输入图片ID');
        return;
    }

    try {
        const response = await fetch(`/api/getimagebyid/?id=${imageId}`);

        if (response.ok) {
            // 创建对象URL来显示图片
            const blob = await response.blob();
            const imageUrl = URL.createObjectURL(blob);

            document.getElementById('coverPreview').src = imageUrl;
            document.getElementById('coverPreviewContainer').style.display = 'block';
            document.getElementById('coverPreviewError').style.display = 'none';

            selectedCoverImageId = parseInt(imageId);
        } else {
            // console.error("H2");
            document.getElementById('coverPreviewContainer').style.display = 'none';
            document.getElementById('coverPreviewError').style.display = 'block';
            document.getElementById('coverPreviewError').textContent = '图片不存在或无法访问';
            selectedCoverImageId = null;
        }
    } catch (error) {
        console.error('预览失败:', error);
        document.getElementById('coverPreviewContainer').style.display = 'none';
        document.getElementById('coverPreviewError').style.display = 'block';
        document.getElementById('coverPreviewError').textContent = '预览失败，请重试';
        selectedCoverImageId = null;
    }
}

// 保存头像
async function saveUserAvatar() {
    const useCurrent = document.getElementById('useCurrentAvatar').checked;

    if (useCurrent) {
        // 不更改头像
        const modal = bootstrap.Modal.getInstance(document.getElementById('editAvatarModal'));
        modal.hide();
        return;
    }

    if (!selectedAvatarImageId) {
        alert('请先选择图片并预览');
        return;
    }

    try {
        console.log("try ", selectedAvatarImageId)
        const response = await fetch('/api/setuserinfo/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({
                type: 'avatar',
                value: selectedAvatarImageId
            })
        });

        if (response.ok) {
            // alert('头像更新成功');
            location.reload();
        } else {
            alert('更新失败，请重试');
        }
    } catch (error) {
        console.error('更新失败:', error);
        alert('更新失败，请重试');
    }
}

// 保存头图
async function saveUserTopImage() {
    const useCurrent = document.getElementById('useCurrentCover').checked;

    if (useCurrent) {
        // 不更改头图
        const modal = bootstrap.Modal.getInstance(document.getElementById('editCoverModal'));
        modal.hide();
        return;
    }

    if (!selectedCoverImageId) {
        alert('请先选择图片并预览');
        return;
    }

    try {
        const response = await fetch('/api/setuserinfo/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({
                type: 'topimage',
                value: selectedCoverImageId
            })
        });

        if (response.ok) {
            // alert('头图更新成功');
            location.reload();
        } else {
            alert('更新失败，请重试');
        }
    } catch (error) {
        console.error('更新失败:', error);
        alert('更新失败，请重试');
    }
}

// 显示模态框时重置状态
document.getElementById('editAvatarModal').addEventListener('show.bs.modal', function () {
    document.getElementById('avatarImageId').value = '';
    document.getElementById('avatarPreviewContainer').style.display = 'none';
    document.getElementById('useCurrentAvatar').checked = false;
    selectedAvatarImageId = null;
});

document.getElementById('editCoverModal').addEventListener('show.bs.modal', function () {
    document.getElementById('coverImageId').value = '';
    document.getElementById('coverPreviewContainer').style.display = 'none';
    document.getElementById('useCurrentCover').checked = false;
    selectedCoverImageId = null;
});


// 显示编辑头像模态框
function showEditAvatarModal() {
    const modal = new bootstrap.Modal(document.getElementById('editAvatarModal'));
    modal.show();
}


// 显示编辑头图模态框
function showEditCoverModal() {
    const modal = new bootstrap.Modal(document.getElementById('editCoverModal'));
    modal.show();
}



// 检查是否是当前用户的主页
async function checkIsOwnProfile(userId) {
    const sessionToken = getCookie('session_token');
    const currentUserId = getCookie('username');

    if (!sessionToken || !currentUserId) {
        return false;
    }

    try {
        // 检查会话是否有效
        const response = await fetch('/api/islogin/');
        const data = await response.json();

        if (data.ok && parseInt(currentUserId) === parseInt(userId)) {
            return true;
        }
    } catch (error) {
        console.error('检查权限失败:', error);
    }

    return false;
}

// 显示/隐藏编辑功能
async function initEditUI(userId) {
    const isOwnProfile = await checkIsOwnProfile(userId);

    if (isOwnProfile) {
        // 显示所有编辑按钮
        document.querySelectorAll('.edit-btn').forEach(btn => {
            btn.style.display = 'block';
        });
        document.querySelectorAll('.edit-overlay').forEach(overlay => {
            overlay.style.display = 'flex';
        });
    }
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function () {
    // 假设userId通过data属性或其他方式传递
    const userId = getCookie('username');
    initEditUI(userId);
});